package com.xxrl.shop.config;

import com.xxrl.shop.common.entity.CommonRuntimeException;
import com.xxrl.shop.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author mis
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    private static final Logger logger = LoggerFactory.getLogger(WebMvcConfig.class);

    @Value("${my.origins.front}")
    private String originFront;
    @Value("${my.origins.admin}")
    private String originAdmin;
    @Value("${my.images.path}")
    private String imagePath;

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        logger.info("accept front address in {}, admin address in {}", originFront, originAdmin);
        registry.addMapping("/**")
                .allowedOrigins(originFront, originAdmin)
                .allowedHeaders("*")
                .allowedMethods("*")
                .allowCredentials(true)
                .maxAge(3600);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/img/**").addResourceLocations(String.format("file:///%s", imagePath));
    }

    @Override
    public void addFormatters(FormatterRegistry registry) {
        // string 转换成 date
        registry.addConverter(new Converter<String, Date>() {
            @Override
            public Date convert(String s) {
                Date target = null;
                if (!StringUtils.isEmpty(s)) {
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    try {
                        target = format.parse(s);
                    } catch (ParseException e) {
                        throw new CommonRuntimeException(String.format("parser %s to Date fail", s));
                    }
                }
                return target;
            }
        });
    }
}
